package trystero.lib.reader;

import java.io.InputStream;

import trystero.lib.auth.ReaderAuth;
import trystero.lib.reader.ReaderRequestStates;
import trystero.lib.http.HTTPClient;
import trystero.lib.http.HTTPRequestState;
import trystero.lib.http.hc.HTTPClientImpl;

import trystero.lib.component.StreamContents;
import trystero.lib.component.parser.StreamContentsParser;
import trystero.lib.component.UnreadCount;
import trystero.lib.component.parser.UnreadCountParser;
import trystero.lib.component.UserInfo;
import trystero.lib.component.parser.UserInfoParser;

import trystero.lib.util.StreamUtils;

public class Reader
{
   ReaderAuth auth;

   public ReaderAuth auth() { return this.auth; }
   public void auth(ReaderAuth auth) { this.auth = auth; }

   public StreamContents streamContents() throws Exception
   {
      HTTPRequestState state = ReaderRequestStates.streamContents();
      auth.authenticate(state);
      HTTPClient client = new HTTPClientImpl();
      InputStream stream = client.get(state);

      StreamContentsParser parser = new StreamContentsParser(stream);
      StreamContents contents = parser.parse();
      return contents;
   }

   public StreamContents streamContents(int count) throws Exception
   {
      HTTPRequestState state = ReaderRequestStates.streamContents(count);
      auth.authenticate(state);
      HTTPClient client = new HTTPClientImpl();
      InputStream stream = client.get(state);

      StreamContentsParser parser = new StreamContentsParser(stream);
      StreamContents contents = parser.parse();
      return contents;
   }

   public UnreadCount unreadCount() throws Exception
   {
      HTTPRequestState state = ReaderRequestStates.unreadCount();
      auth.authenticate(state);
      HTTPClient client = new HTTPClientImpl();
      InputStream stream = client.get(state);

      UnreadCountParser parser = new UnreadCountParser(stream);
      UnreadCount counts = parser.parse();
      return counts;
   }

   public UserInfo userInfo() throws Exception
   {
      HTTPRequestState state = ReaderRequestStates.userInfo();
      auth.authenticate(state);
      HTTPClient client = new HTTPClientImpl();
      InputStream stream = client.get(state);

      UserInfoParser parser = new UserInfoParser(stream);
      UserInfo info = parser.parse();
      return info;
   }

   public boolean editTag(String itemId, boolean add, String tag) throws Exception
   {
      HTTPRequestState state = ReaderRequestStates.editTag(itemId, add, tag);
      auth.authenticate(state);
      auth.stampToken(state);
      HTTPClient client = new HTTPClientImpl();
      InputStream stream = client.post(state);

      String returned = StreamUtils.slurp(stream);
      System.out.println(">>> " + returned);
      return returned.substring(0,2).equals("OK");
   }
}
